B. Divisor Subtraction

本文详细解析了一种特殊算法,该算法通过不断减去输入整数n的最小素数因子直至n变为0,探讨了算法的执行过程,并提供了一种高效的方法来确定算法完全执行所需的步数。

B. Divisor Subtraction

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given an integer number n

. The following algorithm is applied to it:

  1. if n=0
  • , then end algorithm;
  • find the smallest prime divisor d
  • of n
  • ;
  • subtract d
  • from n and go to step 1

    Determine the number of subtrations the algorithm will make.

    Input

    The only line contains a single integer n

    (2≤n≤1010

    ).

    Output

    Print a single integer — the number of subtractions the algorithm will make.

    Examples

    Input

    Copy

    5
    
    Output

    Copy

    1
    
    Input

    Copy

    4
    
    Output

    Copy

    2
    

    Note

    In the first example 5

    is the smallest prime divisor, thus it gets subtracted right away to make a 0

    .

    In the second example 2

    is the smallest prime divisor at both steps.

    题意:给一个n,和一个算法,求这个算法能执行多少次。算法内容:

    1. 如果n等于0,算法结束。

    2. 找到n最小的素数因子d

    3. n-=d,之后回到步骤1

  • 分析:对于输入的n有3种情况:

    1. 素数-------------输出1

    2. 偶数-------------输出n/2

    3. 奇数或合数-------------减去最小的素因子,变为偶数,再执行偶数的计算方法并加1

  • #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <string>
    #include <cstring>
    #include <algorithm>
    #include <cmath>
    using namespace std;
    
    bool IsPrime(long long num)	//num为我们要判断的数
    {
    	for (long long i = 2; i <= sqrt(num); i++)		//最优化的判断方式
    	{
    		if (num%i == 0)
    		{
    			return false;
    		}
    	}
    	return true;
    }
    long long fi(long long n){
        for(long long i = 2;i < n;i++){
            if(n % i == 0)
                return i;
        }
    }
    
    int main()
    {
        long long n;
        while(cin>>n){
            long long t = 0;
            if(n % 2 == 0)
                cout<<n/2<<endl;
            else{
                if(IsPrime(n))
                    cout<<1<<endl;
                else{
                    t = n-fi(n);
                    cout<<t/2+1<<endl;
                }
            }
        }
        return 0;
    }
    

     

=== 小学算式OCR训练系统 === 字符集: 0123456789+-×÷=Xx 类别数: 18 加载数据集: math_problems 错误使用 tranorc11 (第 39 行) 数据集结构错误!\n正确结构示例:\nmath_problems/\n├── 2+3=5/\n│ ├── img1.png\n│ └── img2.png\n├── 10-4=6/\n└── ...\n每个子文件夹名称应是算式标签 这是现在的代码提示,下面我会给出原来的math_problems数据图片生成代码,请根据上面的要求,修改生成代码,从而提供符合要求的数据 % === 图像生成代码 === outputDir = 'math_problems'; if ~exist(outputDir, 'dir') mkdir(outputDir); end numImages = 100; dataTable = table('Size', [numImages, 5], ... 'VariableTypes', {'string', 'string', 'string', 'string', 'string'}, ... 'VariableNames', {'Filename', 'Problem', 'CorrectResult', 'Operator', 'CorrectFlag'}); fontSize = 80; horizontalPadding = 50; verticalPadding = 80; bgColor = [1, 1, 1]; textColor = [0, 0, 0]; fig = figure('Visible', 'off', 'Color', bgColor, ... 'Position', [100, 100, 800, 600], ... 'InvertHardcopy', 'off'); ax = axes('Parent', fig, 'Position', [0, 0, 1, 1], ... 'XLim', [0, 1], 'YLim', [0, 1], 'Visible', 'off'); hold(ax, 'on'); for imgIdx = 1:numImages filename = sprintf('%04d.png', imgIdx); dataTable.Filename(imgIdx) = string(filename); opType = randi(4); switch opType case 1 % 加法 a = randi([10, 90]); b = randi([1, 100-a]); result = a + b; eq = sprintf('%d + %d = ', a, b); operator = 'addition'; case 2 % 减法 a = randi([20, 100]); b = randi([1, a-1]); result = a - b; eq = sprintf('%d - %d = ', a, b); operator = 'subtraction'; case 3 % 乘法 a = randi([1, 10]); b = randi([1, 10]); result = a * b; eq = sprintf('%d × %d = ', a, b); operator = 'multiplication'; case 4 % 除法 divisor = randi([2, 10]); quotient = randi([1, 10]); dividend = divisor * quotient; result = quotient; eq = sprintf('%d ÷ %d = ', dividend, divisor); operator = 'division'; end if rand() > 0.5 displayedResult = result; isCorrect = "1"; else minError = max(1, round(result * 0.8)); maxError = round(result * 1.2); possibleErrors = setdiff(minError:maxError, result); if isempty(possibleErrors) possibleErrors = [result-1, result+1]; end errorIdx = randi(length(possibleErrors)); displayedResult = possibleErrors(errorIdx); isCorrect = "0"; end fullEq = sprintf('%s%d', eq, displayedResult); textWidth = length(fullEq) * fontSize * 0.6; imgWidth = textWidth + 2*horizontalPadding; imgHeight = verticalPadding + fontSize + verticalPadding/2; set(fig, 'Position', [100, 100, imgWidth, imgHeight]); cla(ax); text(ax, 0.5, 0.5, fullEq, ... 'FontSize', fontSize, ... 'FontWeight', 'normal', ... 'Color', textColor, ... 'HorizontalAlignment', 'center', ... 'VerticalAlignment', 'middle'); dataTable.Problem(imgIdx) = string(fullEq); dataTable.CorrectResult(imgIdx) = string(result); dataTable.Operator(imgIdx) = operator; dataTable.CorrectFlag(imgIdx) = isCorrect; % 按运算符分类保存图像 opDir = fullfile(outputDir, operator); if ~exist(opDir, 'dir') mkdir(opDir); end imwrite(getframe(fig).cdata, fullfile(opDir, filename)); end writetable(dataTable, fullfile(outputDir, 'math_problems.xlsx')); close(fig); fprintf('生成完成!\n');
06-19
请根据训练系统的数据集文件夹,重新修改数据集生成代码,原来的代码如下 outputDir = 'math_problems'; if ~exist(outputDir, 'dir') mkdir(outputDir); end numImages = 100; dataTable = table('Size', [numImages, 5], ... 'VariableTypes', {'string', 'string', 'string', 'string', 'string'}, ... 'VariableNames', {'Filename', 'Problem', 'CorrectResult', 'Operator', 'CorrectFlag'}); fontSize = 80; horizontalPadding = 50; verticalPadding = 80; bgColor = [1, 1, 1]; textColor = [0, 0, 0]; availableFonts = {'Arial', 'Times New Roman', 'Courier New', 'Comic Sans MS'}; fig = figure('Visible', 'off', 'Color', bgColor, ... 'Position', [100, 100, 800, 600], ... 'InvertHardcopy', 'off'); ax = axes('Parent', fig, 'Position', [0, 0, 1, 1], ... 'XLim', [0, 1], 'YLim', [0, 1], 'Visible', 'off'); hold(ax, 'on'); imgIdx = 1; maxAttempts = numImages * 3; % 最大尝试次数 existingLabels = containers.Map(); % 标签检测器 while imgIdx <= numImages && maxAttempts > 0 maxAttempts = maxAttempts - 1; % === 生成两位数算式 === opType = randi(4); switch opType case 1 % 加法 (10-99) a = randi([10, 99]); b = randi([10, 99]); result = a + b; eq = sprintf('%d+%d=', a, b); operator = 'addition'; case 2 % 减法 (20-99) a = randi([20, 99]); b = randi([10, min(a-1, 99)]); % 确保结果为正 result = a - b; eq = sprintf('%d-%d=', a, b); operator = 'subtraction'; case 3 % 乘法 (2-20) a = randi([2, 20]); b = randi([2, 20]); result = a * b; eq = sprintf('%d×%d=', a, b); operator = 'multiplication'; case 4 % 除法 (整数结果) divisor = randi([2, 20]); quotient = randi([2, 20]); dividend = divisor * quotient; result = quotient; eq = sprintf('%d÷%d=', dividend, divisor); operator = 'division'; end % === 生成合理错误答案 === if rand() > 0.5 displayedResult = result; isCorrect = "1"; else % 在正确结果附近生成合理错误 errorRange = max(1, round(result*0.2)); % 误差范围 offset = randi([-errorRange, errorRange]); while offset == 0 offset = randi([-errorRange, errorRange]); end displayedResult = result + offset; isCorrect = "0"; end % === 创建安全标签 === labelFolder = sprintf('%s%d', eq, displayedResult); safeLabel = regexprep(labelFolder, '[<>:"/\\|?*]', ''); % 检查标签是否已存在 if isKey(existingLabels, safeLabel) continue; % 跳过重复标签 end existingLabels(safeLabel) = true; % === 生成图像 === fullEq = sprintf('%s%d', eq, displayedResult); selectedFont = availableFonts{randi(length(availableFonts))}; textWidth = length(fullEq) * fontSize * 0.6; imgWidth = textWidth + 2*horizontalPadding; imgHeight = verticalPadding + fontSize + verticalPadding/2; set(fig, 'Position', [100, 100, imgWidth, imgHeight]); cla(ax); text(ax, 0.5, 0.5, fullEq, ... 'FontSize', fontSize, ... 'FontName', selectedFont, ... 'FontWeight', 'normal', ... 'Color', textColor, ... 'HorizontalAlignment', 'center', ... 'VerticalAlignment', 'middle'); % === 保存图像 === imgData = getframe(fig).cdata; labelDir = fullfile(outputDir, safeLabel); if ~exist(labelDir, 'dir') mkdir(labelDir); end filename = sprintf('%04d.png', imgIdx); imwrite(imgData, fullfile(labelDir, filename)); % 更新数据表 dataTable.Filename(imgIdx) = string(filename); dataTable.Problem(imgIdx) = string(fullEq); dataTable.CorrectResult(imgIdx) = string(result); dataTable.Operator(imgIdx) = operator; dataTable.CorrectFlag(imgIdx) = isCorrect; imgIdx = imgIdx + 1; end % === 检查完成度 === if imgIdx <= numImages fprintf('生成不足: %d/%d, 正在补充...\n', imgIdx-1, numImages); dataTable = dataTable(1:imgIdx-1, :); % 调整表格大小 % 补充生成缺失的图像 for i = imgIdx:numImages % 生成唯一标签的简化方法 while true a = randi([10,99]); b = randi([10,99]); op = {'+', '-', '×', '÷'}; opChar = op{randi(4)}; result = randi([10,200]); label = sprintf('%d%s%d=%d', a, opChar, b, result); safeLabel = regexprep(label, '[<>:"/\\|?*]', ''); if ~isKey(existingLabels, safeLabel) existingLabels(safeLabel) = true; break; end end % 生成图像(简化版) fullEq = label; set(fig, 'Position', [100, 100, 600, 300]); % 固定尺寸 cla(ax); text(ax, 0.5, 0.5, fullEq, 'FontSize', fontSize, 'HorizontalAlignment', 'center'); imgData = getframe(fig).cdata; % 保存 labelDir = fullfile(outputDir, safeLabel); mkdir(labelDir); filename = sprintf('%04d.png', i); imwrite(imgData, fullfile(labelDir, filename)); % 更新表格(简化) newRow = {filename, fullEq, '0', 'addition', '0'}; % 占位数据 dataTable = [dataTable; newRow]; end end % === 最终保存 === writetable(dataTable, fullfile(outputDir, 'math_problems.xlsx')); close(fig); %fprintf('生成完成! 创建了%d个子文件夹\n', height(dataTable)); % === 验证重复性 === folders = dir(outputDir); folderCount = sum([folders.isdir]) - 2; % 排除... fprintf('最终生成文件夹数量: %d\n', folderCount); if folderCount < numImages fprintf('警告: 有重复标签未被检测到\n'); end
最新发布
06-21
outputDir = 'math_problems'; if ~exist(outputDir, 'dir') mkdir(outputDir); end % === 新增:内容哈希记录器 === contentHashMap = containers.Map('KeyType', 'char', 'ValueType', 'logical'); labelHashMap = containers.Map('KeyType', 'char', 'ValueType', 'logical'); numImages = 100; dataTable = table('Size', [numImages, 5], ... 'VariableTypes', {'string', 'string', 'string', 'string', 'string'}, ... 'VariableNames', {'Filename', 'Problem', 'CorrectResult', 'Operator', 'CorrectFlag'}); fontSize = 80; horizontalPadding = 50; verticalPadding = 80; bgColor = [1, 1, 1]; textColor = [0, 0, 0]; % === 新增:引入字体变异 === availableFonts = {'Arial', 'Times New Roman', 'Courier New', 'Comic Sans MS'}; fig = figure('Visible', 'off', 'Color', bgColor, ... 'Position', [100, 100, 800, 600], ... 'InvertHardcopy', 'off'); ax = axes('Parent', fig, 'Position', [0, 0, 1, 1], ... 'XLim', [0, 1], 'YLim', [0, 1], 'Visible', 'off'); hold(ax, 'on'); imgIdx = 1; attemptCount = 0; maxAttempts = numImages * 5; % 防止无限循环 while imgIdx <= numImages && attemptCount < maxAttempts attemptCount = attemptCount + 1; % 生成唯一文件名 filename = sprintf('%04d.png', imgIdx); % === 生成随机算式 === opType = randi(4); switch opType case 1 % 加法 a = randi([10, 999]); b = randi([1, 999]); result = a + b; eq = sprintf('%d+%d=', a, b); operator = 'addition'; case 2 % 减法 a = randi([20, 999]); b = randi([1, min(a-1, 999)]); result = a - b; eq = sprintf('%d-%d=', a, b); operator = 'subtraction'; case 3 % 乘法 a = randi([1, 99]); b = randi([1, 99]); result = a * b; eq = sprintf('%d×%d=', a, b); operator = 'multiplication'; case 4 % 除法 divisor = randi([2, 99]); quotient = randi([1, 99]); dividend = divisor * quotient; result = quotient; eq = sprintf('%d÷%d=', dividend, divisor); operator = 'division'; end % === 随机生成正确/错误答案 === if rand() > 0.5 displayedResult = result; isCorrect = "1"; else minError = max(1, round(result * 0.8)); maxError = round(result * 1.2); possibleErrors = setdiff(minError:maxError, result); if isempty(possibleErrors) possibleErrors = [result-1, result+1]; end errorIdx = randi(length(possibleErrors)); displayedResult = possibleErrors(errorIdx); isCorrect = "0"; end % === 创建标签文件夹 === labelFolder = sprintf('%s%d', eq, displayedResult); % 移除非法字符 safeLabel = regexprep(labelFolder, '[<>:"/\\|?*]', ''); % === 新增:标签唯一性检查 === if isKey(labelHashMap, safeLabel) % fprintf('标签重复: %s\n', safeLabel); continue; end % === 生成图像 === fullEq = sprintf('%s%d', eq, displayedResult); % === 新增:字体随机选择 === selectedFont = availableFonts{randi(length(availableFonts))}; textWidth = length(fullEq) * fontSize * 0.6; imgWidth = textWidth + 2*horizontalPadding; imgHeight = verticalPadding + fontSize + verticalPadding/2; set(fig, 'Position', [100, 100, imgWidth, imgHeight]); cla(ax); text(ax, 0.5, 0.5, fullEq, ... 'FontSize', fontSize, ... 'FontName', selectedFont,... % 使用随机字体 'FontWeight', 'normal', ... 'Color', textColor, ... 'HorizontalAlignment', 'center', ... 'VerticalAlignment', 'middle'); % 获取图像数据 imgData = getframe(fig).cdata; % === 新增:内容哈希检测 === imgHash = getImageHash(imgData); if isKey(contentHashMap, imgHash) % fprintf('内容重复: %s (哈希: %s)\n', fullEq, imgHash); continue; end % === 创建标签目录 === labelDir = fullfile(outputDir, safeLabel); if ~exist(labelDir, 'dir') mkdir(labelDir); end % 保存图像 imwrite(imgData, fullfile(labelDir, filename)); % 更新哈希记录 contentHashMap(imgHash) = true; labelHashMap(safeLabel) = true; % 更新数据表 dataTable.Filename(imgIdx) = string(filename); dataTable.Problem(imgIdx) = string(fullEq); dataTable.CorrectResult(imgIdx) = string(result); dataTable.Operator(imgIdx) = operator; dataTable.CorrectFlag(imgIdx) = isCorrect; imgIdx = imgIdx + 1; end % === 新增:实际生成数量处理 === if imgIdx <= numImages dataTable = dataTable(1:imgIdx-1, :); fprintf('实际生成图像: %d/%d (跳过重复项)\n', imgIdx-1, numImages); end writetable(dataTable, fullfile(outputDir, 'math_problems.xlsx')); close(fig); fprintf('生成完成! 创建了%d个子文件夹\n', height(dataTable)); % === 新增:图像哈希函数 === function hash = getImageHash(imgData) % 使用简化哈希提高性能 grayImg = rgb2gray(imgData); smallImg = imresize(grayImg, [16, 16]); % 缩小尺寸 hashVec = smallImg(:) > 128; % 二值化 hash = char(bin2dec(reshape(num2str(hashVec'), 8, [])' + '0')'; end 这是原来的代码,遇到下面的问题:1.小学水平的计算题,所以输出的公式尽量在2位数运算2.如果哈希函数不好使用,直接删去,只要在生成完之后进行文件夹遍历,统计生成文件夹数量,如果不够100个再检查每个里面是否有重复的就可以
06-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值